#include"tim4.h"
uint16_t duty;
void tim4_init(void)
{
    RCC->APB2ENR|=RCC_APB2ENR_IOPBEN;
    RCC->APB1ENR|=RCC_APB1ENR_TIM4EN;

    //2.配置引脚 浮空输入PB6  mode 00    cnf 10
    GPIOB->CRL&=~GPIO_CRL_MODE6;
    GPIOB->CRL&=~GPIO_CRL_CNF6_1;
    GPIOB->CRL|=GPIO_CRL_CNF6_0;

    TIM4->CR1&=~TIM_CR1_DIR;

    TIM4->PSC=71;
    TIM4->ARR=65535;

    //不滤波
    TIM4->CCMR1&=~TIM_CCMR1_IC1F;
    //边沿检测
    TIM4->CCER&=~TIM_CCER_CC1P;
    TIM4->CCER|=TIM_CCER_CC2P;
//映射IC1  TI   IC2 T1
    TIM4->CCMR1|=TIM_CCMR1_CC1S_0;
    TIM4->CCMR1&=~TIM_CCMR1_CC1S_1;

    TIM4->CCMR1|=TIM_CCMR1_CC2S_1;
    TIM4->CCMR1&=~TIM_CCMR1_CC2S_0;
    

    TIM4->CCMR1&=~TIM_CCMR1_IC1PSC;
    TIM4->CCMR1&=~TIM_CCMR1_IC2PSC;

    //配置外部输入的从模式
    TIM4->SMCR|=(TIM_SMCR_TS_2|TIM_SMCR_TS_0);
    TIM4->SMCR&=~TIM_SMCR_TS_1;

    TIM4->SMCR|=TIM_SMCR_SMS_2;
    TIM4->SMCR&=~TIM_SMCR_SMS_1;
    TIM4->SMCR&=~TIM_SMCR_SMS_0;

    TIM4->CCER|=TIM_CCER_CC1E;
    TIM4->CCER|=TIM_CCER_CC2E;


}

void tim4_start(void)
{
    TIM4->CR1|=TIM_CR1_CEN;
}

void tim4_stop(void)
{
    TIM4->CR1&=~TIM_CR1_CEN;
}

uint16_t pwm_freq(void)
{
    return 1000000/TIM4->CCR1;
}

double pwm_duty(void)
{
    return (TIM4->CCR2*1.0/TIM4->CCR1);
}



